package com.tang.kite.benchmark

import com.tang.kite.datasource.unpooled.UnpooledDataSourceFactory
import com.tang.kite.io.Resources
import org.yaml.snakeyaml.Yaml
import javax.sql.DataSource

/**
 * @author Tang
 */
class BaseBenchmark {

    fun getDataSource(): DataSource {
        val inputStream = Resources.getResourceAsStream("kite-config.yml")
        val yaml = Yaml().load<Map<String, Map<String, Map<String, String>>>>(inputStream)
        val kite = yaml["kite"]
        val datasource = kite!!["datasource"] as Map<String, String>
        return UnpooledDataSourceFactory(datasource).getDataSource()
    }

    fun createDatabase(dataSource: DataSource) {
        val database = Resources.getResourceAsStream("schema.sql")
        val connection = dataSource.connection
        val statement = connection.createStatement()
        database.bufferedReader().useLines { lines ->
            val sqlLines = ArrayList<String>()
            val sqlBuilder = StringBuilder()
            lines.forEach { line ->
                if (line.isBlank() || line.startsWith("--")) {
                    return@forEach
                }
                sqlBuilder.append(line)
                if (line.endsWith(";")) {
                    sqlLines.add(sqlBuilder.toString())
                    sqlBuilder.clear()
                }
            }
            for (i in 1..2_000) {
                sqlLines.add("insert into account (username, password, create_time, balance) values ('user$i', 'password$i', '2025-02-21 00:00:00', $i);")
            }
            sqlLines.forEach { sql ->
                try {
                    statement.execute(sql.replace(";", ""))
                } catch (_: Exception) {}
            }
        }
        statement.close()
        connection.close()
    }

    companion object {

        fun getDataSource(): DataSource {
            val baseBenchmark = BaseBenchmark()
            val dataSource = baseBenchmark.getDataSource()
            baseBenchmark.createDatabase(dataSource)
            return dataSource
        }

    }

}
